<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
// import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'

import {
  ElButton,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElSelect,
  ElOption
} from 'element-plus'
import { userIndex, userDetail, userEdit, userGroupSelect, storeSelect } from '@/api/common'
import { Table } from '@/components/Table'
// import { saveTableApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { userType } from '@/api/common/types'
import { ref, reactive, unref, h } from 'vue'
import Write from './components/addWrite.vue'
import { useRouter } from 'vue-router'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// import { TableColumn } from '@/types/table'

import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

const { push } = useRouter()

const { register, tableObject, methods } = useTable<userType>({
  getListApi: userIndex,
  // delListApi: userDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {},
  find: ''
})

const { getList } = methods

getList()

const AddressList = ref([])

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'id',
    label: 'ID',
    width: '90px',
    form: {
      show: false
    }
  },
  {
    field: 'username',
    width: '150px',
    label: t('userDemo.username'),
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'email',
    width: '170px',
    label: '邮箱'
  },
  {
    field: 'password',
    label: t('userDemo.password'),
    width: '110px',
    table: {
      show: false
    }
  },
  {
    field: 'group_id',
    width: '80px',
    label: '权限',
    form: {
      show: true,
      component: 'Select',
      api: async () => {
        const res = await userGroupSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      },
      componentProps: {
        filterable: true
      }
    }
  },
  {
    field: 'store_ids',
    width: '130px',
    label: '所属仓库',
    type: 'string',
    form: {
      show: true,
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        multiple: true
      },
      api: async () => {
        const res = await storeSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      }
    },
    detail: {
      show: false
    }
  },
  {
    field: 'remark',
    width: '150px',
    label: t('userDemo.remark'),
    formatter: (row: userType) => {
      return h(
        'span',
        row.username === 'admin' ? t('userDemo.remarkMessage1') : t('userDemo.remarkMessage2')
      )
    },
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const dialogVisible = ref(false)

const AddAction = () => {
  push('/personnelManagement/loginUserAdd')
}
const dialogTitle = ref('')

// const AddAction = () => {
//   dialogTitle.value = t('exampleDemo.add')
//   tableObject.currentRow = null
//   dialogVisible.value = true
//   actionType.value = ''
// }

const delLoading = ref(false)

const delData = async (row: userType | null, multiple: boolean, rules: string) => {
  if (!checkRlues(rules)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = async (row: userType, type: string, rules: string) => {
  // console.log(rules)
  if (!checkRlues(rules)) return false
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  const userDel = await userDetail(row.id)

  row.password = userDel.data.password
  console.log(row, 'row')
  actionType.value = type
  row.store_ids = row.store_ids.split(',')
  tableObject.currentRow = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as userType
      let obj: any = JSON.parse(JSON.stringify(data))
      obj.store_ids = obj.store_ids.join(',')
      const res = await userEdit(obj, obj.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const { allSchemas } = useCrudSchemas(crudSchemas)
const { setSearchParams } = methods

const selAddress = (id) => {
  let list = AddressList.value
  let data: any = list.find((item: any) => {
    return item.value == id
  })
  return data.label
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
    <div class="mb-10px">
      <!-- <ElButton :loading="delLoading" type="primary" @click="delData(null, true)">
        {{ t('customClearanceForm.import') }}
      </ElButton> -->
      <!-- <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton> -->
      <!-- <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton> -->
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #placestart_id="{ row }"> {{ selAddress(row.placestart_id) }} </template>
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'edit', '20-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <!-- <ElButton type="danger" @click="delData(row, false)">
          {{ t('exampleDemo.del') }}
        </ElButton> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <!-- <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton v-if="actionType == 'edit'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<style lang="less" scoped>
:deep(.el-select) {
  width: 100%;
}
</style>
